//
//  NSAttributedString+CoreText.m
//  TNImageEditing
//
//  Created by Name i on 2021/12/21.
//

#import "NSAttributedString+CoreText.h"
#import <CoreText/CoreText.h>

@implementation NSAttributedString (CoreText)

- (CGSize)tn_sizeWithConstrainedToSize:(CGSize)size {
    if (self.length == 0) return CGSizeZero;
    
    CFAttributedStringRef attributedString = (__bridge CFAttributedStringRef)self;
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributedString);
    CGSize result = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, [self length]), NULL, size, NULL);
    CFRelease(framesetter);
    return result;
}

- (void)tn_drawInContext:(CGContextRef)context
            withPosition:(CGPoint)p
               andHeight:(float)height
                andWidth:(float)width {
    
    CGSize size = CGSizeMake(width, height);
    // 翻转坐标系
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    CGContextTranslateCTM(context, 0, height);
    CGContextScaleCTM(context, 1.0, -1.0);
    
    // 创建绘制区域（路径）
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, CGRectMake(p.x,
                                         height - p.y - size.height,
                                         size.width,
                                         size.height));
    
    // 创建CFAttributedStringRef
    CFAttributedStringRef attributedString = (__bridge CFAttributedStringRef)self;
    
    // 绘制frame
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributedString);
    CTFrameRef ctframe = CTFramesetterCreateFrame(framesetter,
                                                  CFRangeMake(0, 0),
                                                  path,
                                                  NULL);
    CTFrameDraw(ctframe, context);
    CGPathRelease(path);
    CFRelease(framesetter);
    CFRelease(ctframe);
    
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    CGContextTranslateCTM(context,0, height);
    CGContextScaleCTM(context, 1.0, -1.0);
}


- (UIImage * __nullable)tn_createImageWithContentInsets: (UIEdgeInsets)contentInset {
    
        NSRange range = NSMakeRange(0, 1);
        CGSize textSize = [self tn_sizeWithConstrainedToSize:CGSizeMake([UIScreen mainScreen].bounds.size.width-(contentInset.left+contentInset.right), CGFLOAT_MAX)];
        NSDictionary *typingAttributes = [self attributesAtIndex:0 effectiveRange:&range];
        UIColor *textColor = [typingAttributes objectForKey:NSForegroundColorAttributeName];
        CGPoint point = CGPointMake(contentInset.left, contentInset.top);
    
        CGSize size = textSize;
        size.width += (contentInset.left+contentInset.right);
        size.height += (contentInset.top+contentInset.bottom);
        
        @autoreleasepool {
            /** 创建画布 */
            UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
            CGContextRef context = UIGraphicsGetCurrentContext();
            
            // 添加阴影
            UIColor *shadowColor = ([textColor isEqual:[UIColor blackColor]]) ? [UIColor whiteColor] : [UIColor blackColor];
            CGColorRef shadow = [shadowColor colorWithAlphaComponent:0.2f].CGColor;
            CGContextSetShadowWithColor(context, CGSizeMake(1, 1), 3.f, shadow);
            CGContextSetAllowsAntialiasing(context, YES);

            [self tn_drawInContext:context withPosition:point andHeight:textSize.height andWidth:textSize.width];
            
            UIImage *temp = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            return temp;
        }
    return nil;
}


@end
